package com.stonedt.spider.controller.enterprise;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.stonedt.spider.controller.overseas.OverseasInfo;
import com.stonedt.spider.service.InviteService;
import com.stonedt.spider.util.DateUtil;
import com.stonedt.spider.util.UtilConfig;

/**
 * 	投融资信息
 * @date  2020年2月6日 下午2:43:45
 */
@Controller
@RequestMapping("/investmentFinancing")
public class InvestmentFinancingController {
	
//	private final String es_url = "http://s1.stonedt.com:6303";
	private final String es_url = UtilConfig.getURL2().substring(0,UtilConfig.getURL2().length());
	
	private final String investmentrounds_api = "/investment/investmentrounds";
	private final String investmentlist_api =  "/investment/investmentlist";
	private final String getinvestmentdetail_api =  "/investment/getinvestmentdetail";
	
	//展会参展企业
	@RequestMapping(value = "allExhibitionCompany", method = RequestMethod.GET)
	public ModelAndView allExhibitionCompany(ModelAndView mv) {
		mv.addObject("nowArray", DateUtil.getNowDate());
		mv.setViewName("enterpriseData/allExhibitionCompany");
		return mv;
	}
	
	//展会参展企业列表
	@RequestMapping(value = "allExhibitionCompanyList", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	public String allExhibitionCompanyList(String pageNum) {
		String response = "";
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String, String>> list = new ArrayList<>();
		try {
			String param = "{\"timefield\":\"spider_time\",\"times\":\"\",\"size\":\"25\",\"index\":\"stonedt_zhanhui_company\",\"page\":"+pageNum+",\"type\":\"infor\",\"timee\":\"\"}";
	    	JSONObject parseObject = JSONObject.parseObject(param);
	    	System.out.println(parseObject);
	    	RestTemplate client=new RestTemplate();
	    	ResponseEntity<String> responseEntity = client.postForEntity(
	    			"http://dx2.stonedt.com:7120/commonsearch/superdatalist", 
	    			parseObject, 
	    			String.class);
	    	response=responseEntity.getBody();
//		    	response = getJsonHtml("http://dx2.stonedt.com:7120/commonsearch/superdatalist",parseObject);
			System.out.println(response);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("list", list);
			result.put("totalData", 0);
			result.put("totalPage", 1);
		}
		if (StringUtils.isNotBlank(response)) {
			JSONObject parseObject = JSON.parseObject(response);
			String totalData = parseObject.getString("count");
			String totalPage = parseObject.getString("page_count");
			JSONArray jsonArray = parseObject.getJSONArray("data");
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				JSONObject jsonObject2 = jsonObject.getJSONObject("_source");
				Map<String, String> params = JSONObject.parseObject(jsonObject2.toJSONString(), new TypeReference<Map<String, String>>(){});
				list.add(params);
			}
			if (Integer.parseInt(totalData) > 4000) {
				totalPage = "400";
			}
			if (StringUtils.isBlank(totalPage)) {
				totalPage = "1";
			}else if ("0".equals(totalPage)) {
				totalPage = "1";
			}
			result.put("list", list);
			result.put("totalData", totalData);
			result.put("totalPage", totalPage);
		}else {
			result.put("list", list);
			result.put("totalData", 0);
			result.put("totalPage", 1);
		}
		return JSON.toJSONString(result);
	}
	
	//展会企业详情
	@RequestMapping(value = "allExhibitionCompany_detail", method = RequestMethod.GET)
	public ModelAndView allExhibitionCompany_detail(ModelAndView mv, String article_public_id) {
		mv.addObject("article_public_id", article_public_id);
		mv.setViewName("enterpriseData/allExhibitionCompany_detail");
		return mv;
	}
	
	//展会数据
	@RequestMapping(value = "exhibition", method = RequestMethod.GET)
	public ModelAndView exhibition(ModelAndView mv) {
		mv.addObject("nowArray", DateUtil.getNowDate());
		mv.setViewName("enterpriseData/exhibition");
		return mv;
	}
	
	//展会列表
	@RequestMapping(value = "exhibitionList", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	public String happyshoppingList(String pageNum, String matchingmode, String time, String searchkeyword) {
		String response = "";
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String, String>> list = new ArrayList<>();
		try {
			String param = "{\"timefield\":\"spider_time\",\"times\":\"\",\"size\":\"25\",\"index\":\"stonedt_zhanhui\",\"page\":"+pageNum+",\"type\":\"infor\",\"timee\":\"\"}";
	    	JSONObject parseObject = JSONObject.parseObject(param);
	    	System.out.println(parseObject);
	    	response = getJsonHtml("http://dx2.stonedt.com:7120/commonsearch/superdatalist",parseObject);
			System.out.println(response);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("list", list);
			result.put("totalData", 0);
			result.put("totalPage", 1);
		}
		if (StringUtils.isNotBlank(response)) {
			JSONObject parseObject = JSON.parseObject(response);
			String totalData = parseObject.getString("count");
			String totalPage = parseObject.getString("page_count");
			JSONArray jsonArray = parseObject.getJSONArray("data");
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				JSONObject jsonObject2 = jsonObject.getJSONObject("_source");
				Map<String, String> params = JSONObject.parseObject(jsonObject2.toJSONString(), new TypeReference<Map<String, String>>(){});
				list.add(params);
			}
			if (Integer.parseInt(totalData) > 4000) {
				totalPage = "400";
			}
			if (StringUtils.isBlank(totalPage)) {
				totalPage = "1";
			}else if ("0".equals(totalPage)) {
				totalPage = "1";
			}
			result.put("list", list);
			result.put("totalData", totalData);
			result.put("totalPage", totalPage);
		}else {
			result.put("list", list);
			result.put("totalData", 0);
			result.put("totalPage", 1);
		}
		return JSON.toJSONString(result);
	}
	
	//展会企业
	@RequestMapping(value = "exhibitionCompany", method = RequestMethod.GET)
	public ModelAndView exhibitionCompany(ModelAndView mv, String cn_title) {
		mv.addObject("nowArray", DateUtil.getNowDate());
		mv.addObject("cn_title", cn_title);
		mv.setViewName("enterpriseData/exhibitionCompany");
		return mv;
	}
	
	//展会企业列表
	@RequestMapping(value = "exhibitionCompanyList", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	public String exhibitionCompanyList(String pageNum, String cn_title) {
		String response = "";
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String, String>> list = new ArrayList<>();
		try {
			String param = "{\"timefield\":\"spider_time\",\"times\":\"\",\"size\":\"25\",\"and\":[{\"field\":\"cn_title\",\"keyword\":\""+cn_title+"\"}],\"index\":\"stonedt_zhanhui_company\",\"page\":"+pageNum+",\"type\":\"infor\",\"timee\":\"\"}";
	    	JSONObject parseObject = JSONObject.parseObject(param);
	    	System.out.println(parseObject);
	    	RestTemplate client=new RestTemplate();
	    	ResponseEntity<String> responseEntity = client.postForEntity(
	    			"http://dx2.stonedt.com:7120/commonsearch/superdatalist", 
	    			parseObject, 
	    			String.class);
	    	response=responseEntity.getBody();
//	    	response = getJsonHtml("http://dx2.stonedt.com:7120/commonsearch/superdatalist",parseObject);
			System.out.println(response);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("list", list);
			result.put("totalData", 0);
			result.put("totalPage", 1);
		}
		if (StringUtils.isNotBlank(response)) {
			JSONObject parseObject = JSON.parseObject(response);
			String totalData = parseObject.getString("count");
			String totalPage = parseObject.getString("page_count");
			JSONArray jsonArray = parseObject.getJSONArray("data");
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				JSONObject jsonObject2 = jsonObject.getJSONObject("_source");
				Map<String, String> params = JSONObject.parseObject(jsonObject2.toJSONString(), new TypeReference<Map<String, String>>(){});
				list.add(params);
			}
			if (Integer.parseInt(totalData) > 4000) {
				totalPage = "400";
			}
			if (StringUtils.isBlank(totalPage)) {
				totalPage = "1";
			}else if ("0".equals(totalPage)) {
				totalPage = "1";
			}
			result.put("list", list);
			result.put("totalData", totalData);
			result.put("totalPage", totalPage);
		}else {
			result.put("list", list);
			result.put("totalData", 0);
			result.put("totalPage", 1);
		}
		return JSON.toJSONString(result);
	}
	
	//展会企业详情
	@RequestMapping(value = "exhibitionCompany_detail", method = RequestMethod.GET)
	public ModelAndView exhibitionCompanyDetail(ModelAndView mv, String article_public_id) {
		mv.addObject("article_public_id", article_public_id);
		mv.setViewName("enterpriseData/exhibitionCompany_detail");
		return mv;
	}
	
	//展会企业详情数据
	@RequestMapping(value = "exhibitionCompany-detail", method = RequestMethod.POST)
	@ResponseBody
	public String exhibitionCompany_detail(String article_public_id) {
		RestTemplate client=new RestTemplate();
		String params="{\"timefield\":\"spider_time\",\"times\":\"\",\"and\":[{\"field\":\"article_public_id\",\"keyword\":\""+article_public_id+"\"}],\"index\":\"stonedt_zhanhui_company\",\"type\":\"infor\",\"timee\":\"\"}";
		ResponseEntity<String> detailEntity = client.postForEntity(
				"http://dx2.stonedt.com:7120/commonsearch/superdatalist", 
				JSON.parseObject(params), 
				String.class);
		return JSON.parseObject(detailEntity.getBody()).getJSONArray("data").getJSONObject(0).getJSONObject("_source").toJSONString();
	}
	
	/**
	 * 	筛选
	 */
	@RequestMapping(value = "investmentrounds", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	public String investmentrounds() {
		String url = es_url + investmentrounds_api;
		System.err.println(url);
		JSONArray jsonArray = new JSONArray();
		try {
			String sendPost = sendPost(url, "");
			JSONObject parseObject = JSON.parseObject(sendPost);
			if (parseObject.containsKey("aggregations")) {
				JSONObject jsonObject = parseObject.getJSONObject("aggregations");
				if (jsonObject.containsKey("group_by_tags")) {
					JSONObject jsonObject2 = jsonObject.getJSONObject("group_by_tags");
					jsonArray = jsonObject2.getJSONArray("buckets");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return JSON.toJSONString(jsonArray);
	}
	
	/**
	 * 	列表
	 */
	@RequestMapping(value = "investmentlist", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	public String thesisnlist(String pageNum, String matchingmode, String time, String searchkeyword) {
		String times = "", timee = "";
		if (StringUtils.isNotBlank(time)) {
			if ("24h".equals(time)) {
				JSONObject recruitmentMonitorStr = recruitmentMonitorStr(1);
				times = recruitmentMonitorStr.getString("times");
				timee = recruitmentMonitorStr.getString("timee");
			}
			if ("7d".equals(time)) {
				JSONObject recruitmentMonitorStr = recruitmentMonitorStr(7);
				times = recruitmentMonitorStr.getString("times");
				timee = recruitmentMonitorStr.getString("timee");
			}
			if ("30d".equals(time)) {
				JSONObject recruitmentMonitorStr = recruitmentMonitorStr(30);
				times = recruitmentMonitorStr.getString("times");
				timee = recruitmentMonitorStr.getString("timee");
			}
		}
		switch (matchingmode) {
		case "全部":
			matchingmode="0";
			break;
		case "公司名称":
			matchingmode="1";
			break;
		case "项目简介":
			matchingmode="2";
			break;
		}
		Map<String, String> map = new HashMap<>();
//		map.put("rounds", rounds);
		map.put("matchingmode", matchingmode);
		map.put("size", "25");
		map.put("times", times);
		map.put("timee", timee);
		map.put("page", pageNum);
		map.put("keyword", searchkeyword);
		String response = "";
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String, String>> list = new ArrayList<>();
		try {
			response = esArticle(map, investmentlist_api);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("list", list);
			result.put("totalData", 0);
			result.put("totalPage", 1);
		}
		if (StringUtils.isNotBlank(response)) {
			JSONObject parseObject = JSON.parseObject(response);
			String totalData = parseObject.getString("count");
			String totalPage = parseObject.getString("page_count");
			JSONArray jsonArray = parseObject.getJSONArray("data");
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				JSONObject jsonObject2 = jsonObject.getJSONObject("_source");
				Map<String, String> params = JSONObject.parseObject(jsonObject2.toJSONString(), new TypeReference<Map<String, String>>(){});
				params.put("content", params.get("abstract"));
				list.add(params);
			}
			if (Integer.parseInt(totalData) > 5000) {
				totalPage = "500";
			}
			if (StringUtils.isBlank(totalPage)) {
				totalPage = "1";
			}else if ("0".equals(totalPage)) {
				totalPage = "1";
			}
			result.put("list", list);
			result.put("totalData", totalData);
			result.put("totalPage", totalPage);
		}else {
			result.put("list", list);
			result.put("totalData", 0);
			result.put("totalPage", 1);
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 	详情
	 */
	@RequestMapping(value = "detail", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	public String detail(String article_public_id) {
		String url = es_url + getinvestmentdetail_api;
		String params = "article_public_id=" + article_public_id;
		System.err.println(url + "?" + params);
		JSONObject jsonObject = new JSONObject();
		
		try {
			String sendPost = sendPost(url, params);
			jsonObject = JSON.parseObject(sendPost);
//			Object historyArrayStr = jsonObject.get("historyArray");
//			if(null!=historyArrayStr) {
//				String str = historyArrayStr.toString();
//				System.out.println(str);
//				JSONObject historyArrayOb= JSONObject.parseObject(str);
//				System.out.println(historyArrayOb);
//				jsonObject.put("historyArray",historyArrayOb);
//			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return JSON.toJSONString(jsonObject);
	}
	
	public JSONObject recruitmentMonitorStr(Integer days) {
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		LocalDateTime now = LocalDateTime.now();
		String timee = now.format(dateTimeFormatter);
		if (days == null) {
			days = 0;
		}
		String times = now.minusDays(days).format(dateTimeFormatter);
		JSONObject result = new JSONObject();
		result.put("times", times);
		result.put("timee", timee);
		return result;
	}
	
	@RequestMapping(value = "investment-financing", method = RequestMethod.GET)
	public ModelAndView aaa(ModelAndView mv) {
		mv.addObject("nowArray", DateUtil.getNowDate());
		mv.setViewName("enterpriseData/investment-financing");
		return mv;
	}
	
	@RequestMapping(value = "investment-financing-detail", method = RequestMethod.GET)
	public ModelAndView aaaa(ModelAndView mv) {
		mv.setViewName("enterpriseData/investment-financing-detail");
		return mv;
	}
	
//	纳税优企
	@RequestMapping(value = "enterprise-ratepay", method = RequestMethod.GET)
	public ModelAndView ratepay(ModelAndView mv) {
		mv.setViewName("enterpriseData/enterprise-ratepay");
		return mv;
	}
	
	//跳转纳税优企、高新企业详情
	@RequestMapping(value = "toratepay-detail")
	public ModelAndView ratepaydetail(ModelAndView mv,String type,String article_public_id,HttpServletRequest request) {
		mv.setViewName("enterpriseData/enterprise-ratepay-detail");
		if(type.equals("ratepay")) {
			mv.addObject("webName", "纳税优企");
			request.setAttribute("LEFT", "enterprise-ratepay");
		}else if(type.equals("hightech")) {
			mv.addObject("webName", "高新企业");
			request.setAttribute("LEFT", "hightech-enterprises");
		}
		
		request.setAttribute("article_public_id", article_public_id);
		return mv;
	}
	
	//获取纳税优企、高新企业详情
	@RequestMapping(value = "ratepay-detail", method = RequestMethod.POST)
	@ResponseBody
	public String getRatepaydetail(ModelAndView mv,String article_public_id,HttpServletRequest request) {
		request.setAttribute("article_public_id", article_public_id);
		JSONObject json=new JSONObject();
    	String url=UtilConfig.getURL2().substring(0,UtilConfig.getURL2().length()-1)+"/commonsearch/getcommondatadetail";
    	json.put("index", "stonedt_company");
    	json.put("type", "infor");
    	json.put("fieldname", "article_public_id");
    	json.put("fielddata", article_public_id);
    	String data="";
    	try {
			data = OverseasInfo.getJsonHtml(url,json);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	System.out.println(data);
    	JSONObject jsondata=JSONObject.parseObject(data);
    	return jsondata.toJSONString();
	}
	
//	企业网站
	@RequestMapping(value = "enterprise-website", method = RequestMethod.GET)
	public ModelAndView website(ModelAndView mv) {
		mv.setViewName("enterpriseData/enterprise-website");
		return mv;
	}
//	企业信息
	@RequestMapping(value = "enterprise-info", method = RequestMethod.GET)
	public ModelAndView info(ModelAndView mv) {
		mv.setViewName("enterpriseData/enterprise-info");
		return mv;
	}
	
	
//	上市公司
	@RequestMapping(value = "listed-company", method = RequestMethod.GET)
	public ModelAndView listed_company(ModelAndView mv) {
		mv.setViewName("listedcompany/company-list");
		return mv;
	}
	
	@Autowired
	private InviteService inviteService;
	
	//查询上市公司
	@RequestMapping(value = "listedCompany", method = RequestMethod.GET)
	@ResponseBody
	public JSONObject checkCompany(@RequestParam(defaultValue="1",name="pageNum",required=false) Integer pageNum,@RequestParam(defaultValue="10",name="pageSize",required=false) Integer pageSize) {
		
		return inviteService.getListedcompany(pageNum, pageSize);
	}
	
	
	public String esArticle(Map<String, String> map, String api) {
		String size = map.get("size");
		String matchingmode = map.get("matchingmode");
		String times = map.get("times");
		String timee = map.get("timee");
		String page = map.get("page");
		String keyword = map.get("keyword");
		String rounds = map.get("rounds");
		String url = es_url + api;
		String params = "size=" + size + "&matchingmode=" + matchingmode
				+ "&times=" + times + "&timee=" + timee + "&page=" + page + "&keyword=" + keyword
				+ "&rounds=" + rounds;
		System.err.println(url + "?" + params);
		String sendPost = "";
		try {
			sendPost = sendPost(url, params);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sendPost;
	}

	public static String sendPost(String url, String params) throws IOException {
		PrintWriter out = null;
		BufferedReader in = null;
		URL realUrl = new URL(url);
	    URLConnection conn = realUrl.openConnection();  
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		conn.setDoOutput(true);
		conn.setDoInput(true);
		out = new PrintWriter(conn.getOutputStream());
		out.print(params);
		out.flush();
		in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
		StringBuilder response = new StringBuilder();
		String line;
		while((line = in.readLine()) != null){
			response.append(line);
		}
		try {
			if (out != null) {
				out.close();
			}
			if (in != null) {
				in.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return response.toString();
	}
	
	public static String getJsonHtml(String url, JSONObject jsonObject) throws Exception {
		System.err.println(url+jsonObject.toString());
		String result ="";
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		StringEntity postingString = new StringEntity(jsonObject.toString());// json传递
		post.setEntity(postingString);
		post.setHeader("Referer", "http://hotel.qunar.com/cn/shanghai_city/?fromDate=2020-02-13&toDate=2020-02-14&cityName=%E4%B8%8A%E6%B5%B7");
		post.setHeader("Content-type", "application/json");
		HttpResponse response = httpClient.execute(post);
		String content = EntityUtils.toString(response.getEntity());
		result = content;
		System.out.println(result.toString());
		return result;
	}
}
